
module.exports = function (app) {
  const appData = app.globalData;
  if (appData.login && appData.userInfo) { // 不是重新打开的不需要再登陆，解决分享的生命周期问题
    doIHaveLauchParam();
    return;
  }
  wx.getSetting({
    success: function (res) {
      // console.log(res);
      if (!res.authSetting['scope.userInfo']) {
        wx.redirectTo({
          url: '../auth/auth?for=userInfo',
        })
        return;
      }
      console.log('小程序已得到userinfo授权');
      weixinLogin(appData);
    },
    fail: function (res) {
      console.warn('获取wx.settting失败：' + res);
     },
    complete: function (res) { },
  })
}

function weixinLogin(appData) {
  wx.login({
    success: function (res) {
      // console.log(res);
      wx.getUserInfo({
        withCredentials: true,
        lang: 'zh_CN',
        success: function (_res) {
          // console.log(_res)
          appData.userWxInfo = _res.userInfo;
          const currentUserWxInfo = _res.userInfo;
          const lauchOptions = appData.launchOption;
          let _url = appData.serverAddress + 'user/studentLogin?code=' + res.code;
          let shareIdString = '';
          if (lauchOptions.query.sharefromuserid) { // 通过微信分享进入
            shareIdString = '&shareOpenId=' + lauchOptions.query.sharefromuserid;
          } else if (lauchOptions.query.scene) { /// 扫描二维码进入
            shareIdString = '&shareOpenId=' + lauchOptions.query.scene;
          }
          _url += shareIdString;
          wx.request({
            url: _url,
            data: _res,
            header: {},
            method: 'POST',
            success: function (res) {
              // console.log(res);
              if (res.data.code === 0) {
                appData.login = {};
                appData.login.openId = res.data.data.openId;
                appData.login.sessionKey = res.data.data.sessionKey;
                appData.login.token = res.data.data.token;
                // console.log(res.data.data.userInfo);
                appData.userInfo = res.data.data.userInfo;
                // 读取用户的学习信息
                if (res.data.data.userInfo && res.data.data.userInfo.subject > 0) {
                  checkUserStudy(appData);
                }
                // 判断是否有手机
                if (!res.data.data.userInfo.mobile) {
                  wx.redirectTo({
                    url: '../auth/auth?for=authPhone',
                  })
                  return;
                };
                doIHaveLauchParam();
              } else {
                failToast(res.data);
              }
            },
            fail: function (res) {
              failToast(res);
            },
            complete: function (res) { },
          })

        },
        fail: function (res) {
          failToast(res);
        },
        complete: function (res) { },
      })
    },
    fail: function (res) {
      failToast(res);
    },
    complete: function (res) { },
  })
}

const failToast = (d) => {
  console.warn(d);
  wx.showModal({
    title: '操作错误',
    content: JSON.stringify(d),
    showCancel: false,
    confirmText: '关闭',
    confirmColor: '#fe2742',
  })
}

function checkUserStudy(appData) {
  const loadStudy = () => {
    wx.request({
      url: appData.serverAddress + 'student/index/getClasses',
      data: '',
      header: {
        Authorization: appData.login.token,
      },
      method: 'GET',
      success: (res) => {
        // resolv(res);
        if (res.data.code === 0) {
          // console.log(res);
          appData.userStudyInfo = res.data.data;
        } else {
          appData.userStudyInfo = null;
        }
      },
      fail: (res) => {
        appData.userStudyInfo = null;
      },
    })
  }
  loadStudy();
}

function doIHaveLauchParam(){
  let startPage = getApp().globalData.launchPage;
  console.log('start page: ',startPage);
  if (startPage !== 'index') {
    if (startPage === 'offline'){ // 切换到线下老师页面
      wx.redirectTo({ // 不要忘记清掉offlineTeacher
        url: '/pages/offline/offline',
      })
      getApp().globalData.launchPage = 'index';
    }
  }else{
    wx.switchTab({
      url: '/pages/index/index',
    })
    getApp().globalData.launchPage = 'index';
  }
}